(function($) {

var plugin = $.AttachmentsPlugin = {
	//Nom de la classe à instancier /!\ CE NOM DOIT ETRE UNIQUE ET IDENTIQUE AU NOM JQUERY /!\
	name: 'AttachmentsPlugin'
};

//Constructeur
var AttachmentsPlugin = function(options){ // rajouter element
	if(arguments.length) {
		this._init( options );// rajouter element
	} else 
		console.log('Aucun paramètre reçu pour AttachmentsPlugin');
};

AttachmentsPlugin.prototype = {
	defaults: {
		options:{},	
		data: {},
		url: '',
		url_flash: '',
		url_silverlight: ''
	},
	
	_init: function(options){// rajouter element
		var t = this;
		
		// Public
		t.element = $(options.element);
		t.options = $.extend(true, {}, t.defaults, options);
		t.element = (typeof t.options.element != 'undefined') ? t.options.element : null;
		t.idEvent = (typeof t.options.idEvent != 'undefined') ? t.options.idEvent : 0;
		t.attachments = {};
		t.url = t.options.url;
		t.url_flash = t.options.url_flash;
		t.url_silverlight = t.options.url_silverlight;
		
		if(t.idEvent == 0){
			$(t.element).html('<div class="alert">L\'événement doit être enregistré pour enregistrer des pièces jointes');
		} else {
			
			$(t.element).html(t.options.content);
			
			var plupload_settings = {
				// General settings
				runtimes : 'gears,html5,flash,silverlight,browserplus',
				url : t.url,
				max_file_size : '10mb',
				unique_names : false,
				file_data_name: 'uploaded_attachments',
			
				// Flash settings
				flash_swf_url : t.url_flash,
			
				// Silverlight settings
				silverlight_xap_url : t.url_silverlight,
			
				init : {
					FilesAdded: function(up, files) {
						$('#em-plugin-attachments-uploader_refresh').show();
					},					
					FileUploaded: function(up, file, info) {
						var response = JSON.parse(info.response);
						
						if(info.status == 200 && typeof response.result != 'undefined'){
							var attachment = {
								name : file.name,
								id : response.result.id,
								path : response.result.path
							};
	
							var attachments = {};
							attachments[response.result.id] = attachment;
							t.attachments[response.result.id] = attachment;
							
							t.renderAttachments(attachments);	
							
							if(!$('#eventManager').data('eventManager').baseEvent.event.isNew){
								t.submitAttachments();
							}
						} else if(info.status == 200 && typeof response.error != 'undefined'){
							var type = (response.error.code == 400) ? 'warning' : 'error';
							$.pnotify({ title: 'Erreur', text: response.error.message, type: type, history: false });
						} else {
							$.pnotify({ title: 'Erreur serveur !', text: 'Une erreur inconnue est survenue', type: 'error', history: false });
						}
					},
					Error: function(up, args) {
						// Called when a error has occured
						console.log('[error] ', args);
					}
				}
			};
		
			$('.attachment_remove_action').on('click', function(e){ t.deleteAttachment(e, $(this)); });
				
			$('#em-plugin-attachments-uploader_refresh').hide();
			
			$('#em-plugin-attachments-uploader_refresh').on('click', function(e){
				e.preventDefault();
				
				var uploader = $( "#em-plugin-attachments-uploader" );
				uploader.pluploadBootstrap().destroy();
				var widget = uploader.parents('.widget');
				uploader.remove();
				widget.append('<div id="em-plugin-attachments-uploader" class="widget-content no-padding no-border"></div>');	
				$( "#em-plugin-attachments-uploader").pluploadBootstrap(plupload_settings);
				$('#em-plugin-attachments-uploader_refresh').hide();
			});
			
			$( "#em-plugin-attachments-uploader" ).pluploadBootstrap(plupload_settings);
		}
	},
	
	submitAttachments : function(callback){
		var t = this,
			collectionAttachments = $('#em-plugin-attachments-uploader_attachments'),
			dataSend = {
				id_attachments: new Array()
			};
		
		collectionAttachments.find('input[type=hidden][name^=attachment]').each(function(k,v){
			dataSend.id_attachments.push($(this).val());
		});
		
		if(t.idEvent == 0){
			$.pnotify({
                title: "Erreur !",
                text: 'L\'événement doit être créer pour enregistrer les pièces jointes',
                type: "error"
            });
			return;
		}
		
		var urlUpdate = t.options.options.urlBase + 
			t.options.options.urlPattern
				.replace(/idEvent/, t.idEvent)
				.replace(/action/, t.options.options.urlUpdateAction);
		
		$.ajax({
    		type: 'POST',
    		url: urlUpdate,
		  	data: dataSend,
		    dataType: "json"
    	}).done(function(jsonResult) {
    		if(jsonResult && typeof jsonResult.result != 'undefined'){
        		if(jsonResult.result == 200){
        			if(typeof callback == 'function'){
        				callback();
        			} else {
        				$.pnotify({
	                        title: "Terminé !",
	                        text: jsonResult.msg,
	                        type: "success"
	                    });
        			}
        		} else if(jsonResult.result == 500){
        			$.pnotify({
                        title: "Erreur !",
                        text: jsonResult.msg,
                        type: "error"
                    });
        		}
    		} else {
    			alert('La réponse du serveur est incorrecte');
        	}
    	}).fail(function(jqXHR, textStatus, errorThrown) {
    		t.refresh();
    		alert('Une erreur est survenue ('+errorThrown+')');
    	}).always(function(jqXHR, textStatus, errorThrown) {
    	});
	},
	
	renderAttachments : function(attachments){
		$.each(attachments, function(id, attachment){
			var collectionAttachments = $('#em-plugin-attachments-uploader_attachments');
			$('.alert', collectionAttachments).remove();
			
		    var attachmentContent = '<input type="hidden" value="'+id+'" name="attachment_'+$('li', collectionAttachments).size()+'" /><span><i class="icon-attachment"></i></span><code class="text-nowrap" style="width: 75%; vertical-align:middle;"><a class="attachment_remove_action" href="#"><i class="icon-remove"></i> Supprimer</a> - <a href="'+attachment.path+'">'+attachment.name+'</a></code>';
		    var $newAttachment = $('<li class="span12"></li>').appendTo(collectionAttachments);
		    $newAttachment.append(attachmentContent);
			
		    $('.attachment_remove_action').on('click', function(e){ t.deleteAttachment(e, $(this)); });
		});
	},
	
	deleteAttachment : function(e, elem){
		e.preventDefault();
		
		elem.parents('li').remove();

		if($('#services_emailingrequest_attachments > li').size() == 0){
			$('#services_emailingrequest_attachments').append('<li class="alert alert-warning span12">Aucune pièce jointe</li>');
		}
	}
};

$.fn.pluginParticipantsEvent = function(options) {

	var isMethodCall = typeof options === "string",
		args = Array.prototype.slice.call( arguments, 1 ),
		returnValue = this;

	// prevent calls to internal methods
	if ( isMethodCall && options.charAt( 0 ) === "_" ) {
		return returnValue;
	}

	if ( isMethodCall ) {
		this.each(function() {
			var instance = $.data( this, 'AttachmentsPlugin' ),
				methodValue = instance && $.isFunction( instance[options] ) ?
					instance[ options ].apply( instance, args ) :
					instance;

			if ( methodValue !== instance && methodValue !== undefined ) {
				returnValue = methodValue;
				return false;
			}
		});
	} else {
		this.each(function() {
			var instance = $.data( this, 'AttachmentsPlugin' );
			if ( !instance ) {
				$.data( this, 'AttachmentsPlugin', new AttachmentsPlugin( this, options ) );
			}
		});
	}

	return returnValue;
};

function AttachmentsEvent(_plugin){
	var t = this;
	var plugin = _plugin;

	$(plugin.element).html(plugin.settings.content);
	
	$( "#em-plugin-attachments-uploader" ).pluploadBootstrap({
		  
		// General settings
		runtimes : 'gears,html5,flash,silverlight,browserplus',
		url : 'php/plupload.php',
		max_file_size : '256kb',
		chunk_size : '64kb',
		unique_names : true,

		// Resize images on clientside if we can
		resize : { width : 320, height : 240, quality : 90 },

		// Specify what files to browse for
		filters : [
			{title : "Images", extensions : "jpg, jpeg, gif, png"},
	        {title : "Archives", extensions : "zip"}
		],

		// Flash settings
		flash_swf_url : 'plugins/plupload/plupload.flash.swf',

		// Silverlight settings
		silverlight_xap_url : 'plugins/plupload/plupload.silverlight.xap'
	});
}

// Association en tant que plugin jQuery
//$.fn.AttachmentsPlugin = plugin.AttachmentsPlugin;

// Si l'eventManager a été déclaré on le surcharge pour la gestion du plugin
if(typeof $.eventManager != 'undefined'){
	var em = $.eventManager;
	
	// Ajout du plugin au register du manager, il sera instancié par le manager automatiquement
	em.addPluginToRegister('AttachmentsPlugin', AttachmentsPlugin);
	
	em.addCallBackInit(function(){
//		var pluginParticipantsEvent = $('#eventManager').data('eventManager').plugins['ParticipantsEventPlugin'];
//
//		// A la création d'un event dans generalPlugin on envoi le submit des participants
//		if(typeof pluginParticipantsEvent != 'undefined'){
//			pluginParticipantsEvent.onFinishSubmitParticipants = function(jsonResult, dataSend){
//				$('#plug-participants-menu a[data-toggle="tab"][href="#plug-participants-list"]').click();
//
//				pluginParticipantsEvent.refresh();
//				pluginParticipantsEvent.refreshContacts();
//				pluginParticipantsEvent.refreshStates();
//				
//				var pluginAttachments = $('#eventManager').data('eventManager').plugins['AttachmentsPlugin'];
//
//				pluginAttachments.idEvent = jsonResult.idEvent;
//				pluginAttachments.submitAttachments(function(){
//					$.pnotify({
//				        title: "Terminé !",
//				        text: jsonResult.msg,
//				        type: "success"
//				    });
//					
//					if(typeof jsonResult.refresh != 'undefined'){
//						document.location.href = jsonResult.refresh;
//						return;
//					} else {
//						var pluginGeneralEvent = $('#eventManager').data('eventManager').plugins['GeneralEventPlugin'];
//						pluginGeneralEvent.refreshView(dataSend);
//						$('#plug-general-cancel').click();
//					}
//				});	
//			};
//		}
	});
}

})(jQuery);